/**
 * Created by jackliu on 15/12/16.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var ItbBaseModel = require('./ItbBaseModel');


// Schema 结构
var ItbRcmdRewardModel = function(obj){
    ItbBaseModel.call(this,obj);

    /*
      `rr_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
      `user_id` bigint(20) NOT NULL COMMENT '用户id',
      `reward_type` int(3) NOT NULL DEFAULT '0' COMMENT '奖励类型',
      `rcmd_to` bigint(20) DEFAULT NULL COMMENT '被推荐人id',
      `rcmd_by` bigint(20) DEFAULT NULL COMMENT '推荐人id',
      `reward_amt` bigint(20) NOT NULL DEFAULT '0' COMMENT '(本次)奖励数量',
      `exchg_amt` bigint(20) NOT NULL DEFAULT '0' COMMENT '(本次)兑换数量',
      `cur_amt` bigint(20) NOT NULL DEFAULT '0' COMMENT '当前剩余数量',
      `desc` varchar(200) DEFAULT '' COMMENT '备注',
      `create_time` datetime NOT NULL,
      `update_time` datetime NOT NULL,
      `update_by` varchar(50) NOT NULL DEFAULT '',
      `del_flg` int(1) NOT NULL DEFAULT '0' COMMENT '删除flg',
    * */

};
ItbRcmdRewardModel.prototype = new ItbBaseModel();

// 取得表名
ItbRcmdRewardModel.prototype.getTableName = function(){
    return 'itb_rcmd_reward';
};
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
ItbRcmdRewardModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'rr_id='+this.rr_id;
};


/*
* 获取用户推荐统计信息
*
* @author 王俊
* @date 2018-05-15
*
* @param userId 用户唯一标识
* @param callback 回调函数
*           err: 查询失败
*           data: {
*               totalRecommend: 总推荐人数
*               currentReward: 可兑换天数
*               totalExchangeReward: 已兑换天数
*           }
*
* */
ItbRcmdRewardModel.prototype.summaryUserRecommendBriefInfo = function (userId, callback) {
    pool.pool.getConnection(function(getConErr, connection) {
        if (getConErr) {
            console.log('ItbRcmdRewardModel.prototype.summaryUserRecommendBriefInfo getConErr: '+getConErr);
            return callback(getConErr, null);
        }
        var sql =
            ' SELECT x.totalRecommend, ' +
            '        y.currentReward, ' +
            '        z.totalExchangeReward ' +
            ' FROM ' +
            '   ( SELECT COUNT(0) AS totalRecommend ' +
            '    FROM itbour.itb_rcmd_reward irr ' +
            '    WHERE irr.rcmd_by = ' + userId +
            '      AND irr.rcmd_to > 0 ' +
            '      AND irr.user_id != ' + userId +
            '      AND irr.del_flg = 0) x, ' +          // 计算总推荐个数
            '   (SELECT irr.cur_amt AS currentReward ' +
            '    FROM itbour.itb_rcmd_reward irr ' +
            '    WHERE irr.user_id = ' + userId +
            '      AND irr.del_flg = 0 ' +
            '    ORDER BY irr.rr_id DESC LIMIT 1) y, ' +     // 计算可兑换天数
            '   ( SELECT SUM(irr.exchg_amt) AS totalExchangeReward ' +
            '    FROM itbour.itb_rcmd_reward irr ' +
            '    WHERE irr.user_id = ' + userId +
            '      AND irr.exchg_amt > 0 ' +
            '      AND irr.del_flg = 0) z ';            // 计算已兑换天数
        console.log(sql);
        connection.query(sql, function(queryErr, result) {
            connection.release();

            if(queryErr) {
                console.log('ItbRcmdRewardModel.prototype.summaryUserRecommendBriefInfo queryErr: '+queryErr);
                return callback(queryErr, null);
            }
            if(!result || result.length <=0) {
                return callback(queryErr, {});
            }
            return callback(queryErr, result[0]);
        });
    });
};

/**
 * 获取 获取邀请用户列表 功能相关的 sql
 *
 * @author 王俊
 * @date 2018-05-15
 *
 * @param {Boolean} beForCnt 是否是获取个数
 * @param {Object} options 请求参数
 * @param {Number} options.userId 请求参数
 * @param {Number} [options.pageNum] 请求参数
 * @param {Number} [options.pageSize] 请求参数
 *
 * @return {String} sql 对应的 sql
 */
function sql_getRcmdUsersList(beForCnt, options) {

    var sql = '';
    if(beForCnt) {
        sql += ' SELECT COUNT(0) AS totalCnt ';
    } else {
        sql +=
            ' SELECT DATE_FORMAT(irr.create_time, "%Y-%m-%d") AS timeStr, ' +
            '        UNIX_TIMESTAMP(irr.create_time) AS timestamp, ' +
            '        concat(left(iu.mobile, 7), "****") AS mobile ';
    }

    sql +=
        ' FROM itbour.itb_rcmd_reward irr, ' +
        '      itb_user iu ' +
        ' WHERE iu.del_flg = 0 ' +
        '   AND iu.user_id = irr.user_id'+
        '   AND iu.user_type = 1 ' +
        '   AND irr.user_id !=  ' + options.userId +
        '   AND irr.rcmd_by =  ' + options.userId +
        '   AND irr.rcmd_to > 0 ' +
        '   AND irr.del_flg = 0 ' +
        ' ORDER BY irr.create_time DESC ';
    if(!beForCnt &&
        typeof options.pageNum !== 'undefined' && options.pageNum !== null &&
        typeof options.pageSize !== 'undefined' && options.pageSize !== null
    ) {
        var skipCnt = options.pageNum*options.pageSize;
        sql += " LIMIT " + skipCnt + "," + options.pageSize;
    }
    return sql;
}

/**
 * 获取推荐用户列表
 *
 * @author 王俊
 * @date 2018-05-15
 *
 * @param {Object} options 请求参数
 * @param {Number} options.userId 请求参数
 * @param {Number} options.pageNum 请求参数
 * @param {Number} options.pageSize 请求参数
 * @param {Function} callback 回调函数
 *                      err: 查询失败
 *                      list: 用户列表
 */
ItbRcmdRewardModel.prototype.getRcmdUsersList = function (options, callback) {
    pool.pool.getConnection(function(getConErr, connection) {
        if (getConErr) {
            console.log('ItbRcmdRewardModel.prototype.getRcmdUsersList getConErr: '+getConErr);
            return callback(getConErr, null);
        }
        var sql = sql_getRcmdUsersList(false, options);
        console.log(sql);
        connection.query(sql, function(queryErr, result) {
            connection.release();

            if(queryErr) {
                console.log('ItbRcmdRewardModel.prototype.getRcmdUsersList queryErr: '+queryErr);
                return callback(queryErr, null);
            }
            return callback(queryErr, result);
        });
    });
};

/**
 * 获取推荐用户总个数
 *
 * @author 王俊
 * @date 2018-05-15
 *
 * @param {Object} options 请求参数
 * @param {Number} options.userId 请求参数
 * @param {Function} callback 回调函数
 *                      err: 查询失败
 *                      totalCnt 总个数
 */
ItbRcmdRewardModel.prototype.getRcmdUsersListCnt = function (options, callback) {
    pool.pool.getConnection(function(getConErr, connection) {
        if (getConErr) {
            console.log('ItbRcmdRewardModel.prototype.getRcmdUsersList getConErr: '+getConErr);
            return callback(getConErr, null);
        }
        var sql = sql_getRcmdUsersList(true, options);
        console.log(sql);
        connection.query(sql, function(queryErr, result) {
            connection.release();

            if(queryErr || !result || result.length <=0) {
                console.log('ItbRcmdRewardModel.prototype.getRcmdUsersList queryErr: '+queryErr);
                return callback(queryErr || '查询失败', null);
            }
            return callback(queryErr, result[0].totalCnt);
        });
    });
};

/**
 * 更新推荐奖励表信息
 *
 * @author 王俊
 * @date 2018-05-15
 *
 * @param {Object} options 请求参数
 * @param {Number} options.userId       更新人
 * @param {Number} options.rcmdTo       被推荐人 id
 * @param {Number} options.rcmdBy       推荐人 id
 * @param {Number} options.rewardType   奖励类型, 默认为0
 * @param {Number} options.rewardAmt    奖励数量
 * @param {Number} options.exchangeAmt  兑换数量
 * @param {Number} options.autoExchange 是否自动兑换
 * @param {String} options.desc 请求参数
 *
 * @param {Function} callback 回调函数
 *                      err: 处理失败
 *                      retCode: 处理结果
 */
ItbRcmdRewardModel.prototype.updRcmdRewardInfo = function (options, callback) {
/*
	# 更新用户奖励纪录
	# p_user_id(IN): 用户id
	# p_rcmd_to(IN): 该用户推荐谁
	# p_rcmd_by(IN): 该用户被谁推荐
	# p_reward_type(IN): 奖励类型
	# p_reward_amt(IN): 获得奖励值
	# p_exchg_amt(IN): 兑换奖励值
	# p_desc(IN): 备注
    # p_exchg_flg(IN) 兑换标记: 0仅插入本次纪录; 1如果本次纪录是获得奖励,则自动兑换本次奖励
	# result_code(OUT): 0成功, 1参数错误, 2奖励值不足以兑换
    call `proc_upd_itb_rcmd_reward`(2,0,1,0,10,0,'test',1,@outRet)
*
* */

    pool.pool.getConnection(function(getConErr, connection) {
        if (getConErr) {
            console.log('ItbRcmdRewardModel.prototype.updRcmdRewardInfo getConErr: '+getConErr);
            return callback(getConErr, null);
        }
        var sql = ' call `proc_upd_itb_rcmd_reward`( '
            + options.userId + ','
            + options.rcmdTo + ','
            + options.rcmdBy + ','
            + options.rewardType + ','
            + options.rewardAmt + ','
            + options.exchangeAmt + ','
            + '"' + options.desc +  '"' +','
            + options.autoExchange + ','
            + ' @outRet'


            + ' )';
        console.log(sql);
        connection.query(sql, function(queryErr, results) {
            connection.release();
            if(queryErr || !results || results.length <=0) {
                return callback(queryErr || '处理失败', null);
            }
            return callback(queryErr, results[0].result_code);
        });
    });

};


// 导出
module.exports = ItbRcmdRewardModel;